package org.dromara.job.snailjob;

import cn.hutool.json.JSONObject;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.core.util.JsonUtil;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.oce.constant.CommonConstantsJuLang;
import org.dromara.oce.domain.OceAdvertiserEverydayCost;
import org.dromara.oce.domain.OceAdvertiserReferralRelation;
import org.dromara.oce.mapper.OceAdvertiserEverydayCostMapper;
import org.dromara.oce.mapper.OceAdvertiserReferralRelationMapper;
import org.dromara.oce.utils.CommonConstants;
import org.dromara.oce.utils.DateTimeUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 更新链接绑定状态
 * @author opensnail
 * @date 2024-05-17
 */
@Component
@JobExecutor(name = "referralUpdateJob")
@RequiredArgsConstructor
public class ReferralUpdateJobExecutor {

    private final OceAdvertiserReferralRelationMapper referralRelationMapper;
    private final OceAdvertiserEverydayCostMapper oceAdvertiserEverydayCostMapper;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        SnailJobLog.REMOTE.info("referralUpdateJob. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
        JSONObject jsonObject = new JSONObject(JsonUtil.toJsonString(jobArgs));
        String jobParamStr = jsonObject.getStr("jobParams");
        List<String> params = null;
        long notCostDayNum;
        if(StringUtils.isNotBlank(jobParamStr)){
            params = Arrays.asList(jobParamStr.split("_"));
        }
        if(CollectionUtils.isNotEmpty(params)){
            notCostDayNum = Long.parseLong(params.get(0));
        } else {
            notCostDayNum = 4L;
        }
        Long endTime = DateTimeUtil.getBeginTimestampSecond(LocalDateTime.now());
        Long startTime = endTime - (notCostDayNum - 1) * 24 * 60 * 60;//最近4天，4天都没得消耗
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqwCost = Wrappers.lambdaQuery();
        lqwCost.ge(OceAdvertiserEverydayCost::getThatdayTimestamp, startTime);
        lqwCost.le(OceAdvertiserEverydayCost::getThatdayTimestamp, endTime);
        lqwCost.eq(OceAdvertiserEverydayCost::getCost, 0L);
        lqwCost.groupBy(OceAdvertiserEverydayCost::getReferralLinkId);
        lqwCost.having(" count(referral_link_id) = " + notCostDayNum );
        List<OceAdvertiserEverydayCost> advertiserEverydayCosts = oceAdvertiserEverydayCostMapper.selectJobList(lqwCost);
        if(CollectionUtils.isNotEmpty(advertiserEverydayCosts)){
            OceAdvertiserReferralRelation relation = new OceAdvertiserReferralRelation();
            relation.setPullStatus(CommonConstants.PULL_STATUS_OFF);
            List<Long> referralLinkIds = advertiserEverydayCosts.stream().map(OceAdvertiserEverydayCost::getReferralLinkId).distinct().toList();;
            LambdaQueryWrapper<OceAdvertiserReferralRelation> lqw = Wrappers.lambdaQuery();
            lqw.eq(OceAdvertiserReferralRelation::getPullStatus, CommonConstantsJuLang.PULL_STATUS_ON);
            lqw.in(OceAdvertiserReferralRelation::getReferralLinkId, referralLinkIds);
            int count = referralRelationMapper.update(relation,lqw);
            SnailJobLog.REMOTE.info("已经有"+notCostDayNum+"天没有消耗的推广链接数量:{} 已经更新状态成功", count);
        }
        LambdaQueryWrapper<OceAdvertiserReferralRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(OceAdvertiserReferralRelation::getPullStatus, CommonConstantsJuLang.PULL_STATUS_ON);
        List<OceAdvertiserReferralRelation> referralRelations = referralRelationMapper.selectJobList(lqw);
        if (CollectionUtils.isNotEmpty(referralRelations)) {
            List<OceAdvertiserReferralRelation> updateRelations = new ArrayList<>();
            for (OceAdvertiserReferralRelation relation : referralRelations) {
                if (!ObjectUtils.isEmpty(relation.getEndTime()) && LocalDateTime.now().isAfter(relation.getEndTime())) {
                    SnailJobLog.REMOTE.info("推广链接id={}，已经超过有效时间：{},只更新昨日的数据", relation.getReferralLinkId(), relation.getEndTime());
                    relation.setPullStatus(CommonConstants.PULL_STATUS_OFF);
                    updateRelations.add(relation);
                }
            }
            if (CollectionUtils.isNotEmpty(updateRelations)) {
                boolean flag = referralRelationMapper.updateBatchById(updateRelations);
                if (flag) {
                    SnailJobLog.REMOTE.info("已经超过有效时间的推广链接数量:{} 已经更新状态成功", updateRelations.size());
                }
            }
        }
        return ExecuteResult.success("更新巨量推广链接启用状态执行成功!");
    }
}
